import axios from 'axios'
import { getApiBaseUrl } from '../config'

// API响应类型定义
export interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: string
}

// 创建axios实例
const api = axios.create({
  baseURL: getApiBaseUrl(),
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data as any
  },
  (error) => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

// 服务API
export const ServiceAPI = {
  // 获取所有服务状态
  getServices: (): Promise<ApiResponse> => api.get('/services'),
  
  // 启动服务
  startService: (serviceId: string): Promise<ApiResponse> => api.post(`/services/${serviceId}/start`),
  
  // 停止服务
  stopService: (serviceId: string): Promise<ApiResponse> => api.post(`/services/${serviceId}/stop`),
  
  // 重启服务
  restartService: (serviceId: string): Promise<ApiResponse> => api.post(`/services/${serviceId}/restart`),
  
  // 获取服务日志
  getServiceLogs: (serviceId: string, lines: number = 100): Promise<ApiResponse> => 
    api.get(`/services/${serviceId}/logs?lines=${lines}`),
  
  // 添加服务
  addService: (serviceConfig: any): Promise<ApiResponse> => api.post('/services', serviceConfig),
  
  // 删除服务
  deleteService: (serviceId: string): Promise<ApiResponse> => api.delete(`/services/${serviceId}`),
  
  // 健康检查
  healthCheck: (): Promise<ApiResponse> => api.get('/health')
}